package com.hice.demo.sbdbra.common.util.security;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.buf.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
    private static Logger log = LoggerFactory.getLogger(AESUtil.class);

    public static String encryptForString(String complement, String key, String iv, String content) {
        byte[] bytes = encrypt(complement, key, iv, content);
        return HexUtils.toHexString(bytes);
    }

    public static byte[] encrypt(String complement, String key, String iv, String content) {
        try {
            if (StringUtils.isBlank(complement)) {
                complement = "AES/CBC/PKCS5Padding";
            }
            Cipher cipher = Cipher.getInstance(complement);
            byte[] dataBytes = content.getBytes();

            if (complement.equals("AES/CBC/NoPadding")) {
                int blockSize = cipher.getBlockSize();
                int plaintextLength = dataBytes.length;
                if (plaintextLength % blockSize != 0) {
                    plaintextLength += blockSize - plaintextLength % blockSize;
                }
                byte[] plaintext = new byte[plaintextLength];
                System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

                dataBytes = plaintext;
            }

            byte[] raw = key.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

            cipher.init(1, skeySpec, ivSpec);

            byte[] encrypted = cipher.doFinal(dataBytes);

            return encrypted;
        } catch (Exception e) {
            log.error("AES encrypt error", e);
        }
        return null;
    }

    public static String decrypt(String complement, String key, String iv, String content) {
        byte[] bytes = HexUtils.fromHexString(content);

        return decrypt(complement, key, iv, bytes);
    }

    public static String decrypt(String complement, String key, String iv, byte[] bytes) {
        try {
            if (StringUtils.isBlank(complement)) {
                complement = "AES/CBC/PKCS5Padding";
            }
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance(complement);
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

            cipher.init(2, skeySpec, ivSpec);

            byte[] decrypted = cipher.doFinal(bytes);

            return new String(decrypted);
        } catch (Exception e) {
            log.error("AES decrypt error", e);
        }
        return null;
    }
}